package ink.xiaobaibai.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import ink.xiaobaibai.common.BuyPayBo;
import ink.xiaobaibai.common.PageInfo;
import ink.xiaobaibai.dao.BuyOrderDao;
import ink.xiaobaibai.entity.BuyOrder;
import ink.xiaobaibai.entity.LogisticsBuy;
import ink.xiaobaibai.entity.ProductDevice;
import ink.xiaobaibai.service.IBuyOrderService;
import ink.xiaobaibai.service.ILogisticsBuyService;
import ink.xiaobaibai.service.IProductDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xiaobaibai
 * @since 2021-06-12
 */
@Service
public class BuyOrderServiceImpl extends ServiceImpl<BuyOrderDao, BuyOrder> implements IBuyOrderService {

    private static final String BuyOrderUserInfoPre = "BuyOrderUserInfoPre:";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ILogisticsBuyService logisticsBuyService;

    @Autowired
    private IProductDeviceService productDeviceService;

    @Override
    public void setBuyPayBoInfo(BuyPayBo buyPayBo, Integer userId) {
        String key = BuyOrderUserInfoPre + buyPayBo.getAdminUserId() + "@" + userId;
        this.stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(buyPayBo), 15, TimeUnit.MINUTES);
    }

    @Override
    public LogisticsBuy getLogisticsBuy(Integer adminUserid, Integer userId) {
        String key = BuyOrderUserInfoPre + adminUserid + "@" + userId;
        String str = this.stringRedisTemplate.opsForValue().get(key);
        if (str == null) {
            return new LogisticsBuy("未知", "未知", "未知");
        }
        BuyPayBo buyPayBo = JSON.parseObject(str, BuyPayBo.class);
        LogisticsBuy logisticsBuy = new LogisticsBuy(buyPayBo.getName(), buyPayBo.getPhone(), buyPayBo.getAddress());
        if (buyPayBo.getProductId() != null) {
            Integer productId = buyPayBo.getProductId();
            ProductDevice productDevice = this.productDeviceService.getById(productId);
            if (productDevice != null) {
                logisticsBuy.setRemarks(productDevice.getName() + "^" + productDevice.getType());
            }
        }
        return logisticsBuy;
    }

    @Override
    public PageInfo<LogisticsBuy> getLogisticsListByNoSend(Integer pageNum, Integer pageSize) {
        Integer count = this.baseMapper.getLogisticsListByNoSendCount();
        if (count == 0) {
            return new PageInfo<>(new ArrayList<>(), count, pageSize);
        }
        List<LogisticsBuy> list = this.baseMapper.getLogisticsListByNoSend((pageNum - 1) * pageSize, pageSize);
        return new PageInfo<>(list, count, pageSize);
    }

}
